package com.cloudfun.campusshare.configuration.jpa.specification;

import com.cloudfun.campusshare.configuration.jpa.util.PropertyFilter;
import com.cloudfun.campusshare.configuration.jpa.util.RestrictionNames;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * @author 王溪源
 * @ClassName: SpecificationUtil
 * @Description:
 **/
public class SpecificationUtil {
    public static Specification get(List<PropertyFilter> filters) {
        return new PropertyFilterSpecification (filters);
    }

    public static Specification get(PropertyFilter filter) {
        return new PropertyFilterSpecification (filter);
    }

    public static Specification get(String propertyName, Object value) {
        return get (propertyName, value, RestrictionNames.EQ);
    }

    private static Specification get(String propertyName, Object value, String restrictionName) {
        return new PropertySpecification (propertyName, value, restrictionName);
    }

    public static Path<?> getPath(String propertyName, Root<?> root) {
        Path<?> path;
        if (StringUtils.contains (propertyName, ".")) {
            String[] rootNames = StringUtils.splitByWholeSeparator (propertyName, ".");
            path = root.get (rootNames[0]);
            for (int i = 1; i < rootNames.length; i++) {
                path = path.get (rootNames[i]);
            }
        } else {
            path = root.get (propertyName);
        }
        return path;
    }
}
